<template>
    <el-card class="border-0">
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="24">
                <el-col :span="5" :offset="0">
                    <el-form-item label="产品名称">
                        <el-input size="small" v-model="searchForm.name" placeholder="产品名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="0">
                    <el-form-item label="产品类型">
                        <!-- <el-select size="small" v-model="searchForm.type" clearable>
                            <el-option v-for="(item, index) in productTypeList" :label="item.value" :value="item.code"
                                :key="index"></el-option>
                        </el-select> -->
                        <el-tree-select :props="{ label: 'name', value: 'code' }" style="width: 240px"
                            v-model="searchForm.type" :data="productTypeList" :render-after-expand="false" />
                    </el-form-item>
                </el-col>

                <el-col :span="11">
                    <div class="flex items-center justify-end">
                        <el-button size="small" type="primary" @click="getData(1)">搜索</el-button>
                        <el-button size="small" @click="resetSearchForm">重置</el-button>
                        <el-button size="small" type="primary" @click="handleCreate">新增</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <el-table :data="tableData" stripe style="width: 100%;min-height: auto;"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
            <el-table-column label="产品id" align="center" prop="id"></el-table-column>

            <el-table-column label="产品名称" align="center" prop="name"></el-table-column>
            <el-table-column label="产品名称En" align="center" prop="nameEn"></el-table-column>
            <el-table-column label="产品类型" align="center" prop="typeName"></el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" size="small" text @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="primary" size="small" text @click="handleDetail(scope.row)">详情</el-button>
                    <el-popconfirm title="确定删除产品吗?" @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button type="primary" size="small" text>删除</el-button>
                        </template>
                    </el-popconfirm>

                </template>

            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="searchForm.total"
                :current-page="searchForm.pageNo" :page-size="searchForm.pageSize" @current-change="getData" />
        </div>
    </el-card>

    <FormDrawer size="60%" ref="formDrawerRef" :showSubBtn="showSubBtn" :title="drawerTitle" @submit="handleSubmit"
        @isClosed="isClosed">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

            <el-form-item label="产品名称" prop="name">
                <el-input :disabled="!showSubBtn" v-model="form.name" placeholder="产品名称"></el-input>
            </el-form-item>
            <el-form-item label="产品名称En" prop="nameEn">
                <el-input :disabled="!showSubBtn" v-model="form.nameEn" placeholder="产品名称En"></el-input>
            </el-form-item>
            <el-form-item label="产品类型" prop="type">
                <el-tree-select :props="{ label: 'name', value: 'code' }" :disabled="!showSubBtn" v-model="form.type"
                    :data="productTypeList" :render-after-expand="false" />
            </el-form-item>
            <el-form-item label="操作手册" prop="file" required>
                <el-upload :disabled="!showSubBtn" class="upload-demo" ref="upload" accept=".docx,.zip,.pdf,.jpg,.png,.xlsx,.xls,.ppt,.pptx"
                    action="#" :multiple="true" :limit="1" :on-change="fileChange" :on-remove="fileRemove"
                    :file-list="form.fileList" :before-upload="beforeUpload" :on-exceed="handleExceed"
                    :auto-upload="false">
                    <el-button size="small" :disabled="!showSubBtn" type="primary">选取文件</el-button>
                    <div :disabled="!showSubBtn" class="el-upload__tip" style="display: inline-block;margin-left: 20px">
                        请选择PDF、PPT、Word、Excel、图片或者ZIP包文件</div>
                </el-upload>
            </el-form-item>
            <el-tabs>
                <el-tab-pane label="中文">
                    <el-form-item label="文章内容" prop="content">
                        <Editor :disable="editorRef_disable" :contentHtml="form.content" ref="editorRef" />
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="英文">
                    <el-form-item label="文章内容" prop="content">
                        <Editor :disable="editorRef_disable" :contentHtml="form.contentEn" ref="editorRef_en" />
                    </el-form-item>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </FormDrawer>
</template>

<script setup>
import { reactive, onMounted, ref, computed } from 'vue'
import { product_addOrUpdate_api, product_detail_api, product_getProductCategory_api, product_pageQuery_api, product_delete_api } from '~/api/official_article_api';
import FormDrawer from "~/components/FormDrawer.vue";
import Editor from "~/components/editor.vue";
import { toast, toastWarn } from "~/composables/util"
import '@wangeditor/editor/dist/css/style.css'


// ------------- data -----------------
const productTypeList = ref([])
const searchFormInit = {
    name: '',
    type: '',
    total: 1,
    pageNo: 1,
    pageSize: 10,
}
const searchForm = reactive(searchFormInit)
const tableData = ref([])
const formDrawerRef = ref(null)
const formRef = ref(null)
const showSubBtn = ref(false)
const drawerTitle = ref('')
const editorRef = ref(null)
const editorRef_en = ref(null)
const editorRef_disable = ref(true)

const formInit = {
    id: '',
    name: '',
    fileList: [],
    nameEn: '',
    type: '',
    content: '',
    contentEn: '',
    productItemList: [
        { id: '', lang: 'zh', productId: '', content: '' },
        { id: '', lang: 'en', productId: '', content: '' },
    ]
}
const form = reactive({ ...formInit })
const rules = {
    name: [
        { required: true, message: '产品名称不能为空', trigger: 'change' }
    ],
    nameEn: [
        { required: true, message: '产品英文名称不能为空', trigger: 'change' }
    ],
    type: [
        { required: true, message: '产品类型不能为空', trigger: 'change' }
    ],
    content: [
        { required: true, message: '产品详情页内容不能为空', trigger: 'change' }
    ],
    contentEn: [
        { required: true, message: '产品英文详情页内容不能为空', trigger: 'change' }
    ],
}


// ------------- fucntion -------------------
// 文件改变
const fileChange = (file, fileList) => {
    console.log("=======fileChange file========" + JSON.stringify(file))
    console.log("=======fileChange fileList========" + JSON.stringify(fileList))
    form.fileList = fileList;
}

// 文件移除
const fileRemove = (file, fileList) => {
    console.log("=======fileRemove fileList========" + JSON.stringify(form.fileList))
    form.fileList = fileList
    console.log("=======fileRemove fileList final ========" + JSON.stringify(fileList))
}

// 文件超出个数限制
const handleExceed = (file, fileList) => {
    // console.log("=======handleExceed========" + JSON.stringify(fileList))
    toastWarn('一次性最多上传1个文件');
}

// 上传前 文件校验
const beforeUpload = (file, fileList) => {
    // console.log("=======beforeUpload fileList========" + JSON.stringify(fileList))
    let allowSize = 0
    fileList.forEach(file => {
        allowSize += file.size
    })
    const isLt2M = allowSize / 1024 / 1024 <= 50
    if (!isLt2M) {
        toastWarn('单次上传文件大小不能超过 50MB!')
        return false;
    }
    return true;
}
//产品类型下拉框
function getProductTypeList() {
    product_getProductCategory_api().then(res => {
        productTypeList.value = res
    })
}

function getData(p) {
    if (typeof p == "number") {
        searchForm.pageNo = p
    }
    product_pageQuery_api(searchForm).then(res => {
        console.log("产品分页查询结果：", res)
        tableData.value = res.records
        searchForm.total = parseInt(res.total)
    })
}

// 点击新增按钮
function handleCreate() {
    drawerTitle.value = '新增'
    resetForm({
        id: '',
        name: '',
        file: null,
        nameEn: '',
        type: '',
        content: '',
        contentEn: '',
        productItemList: [
            { id: '', lang: 'zh', productId: '', content: '' },
            { id: '', lang: 'en', productId: '', content: '' },
        ]
    })
    form.id = ''
    form.content = ''
    form.contentEn = ''
    //打开弹窗
    showSubBtn.value = true;
    editorRef_disable.value = false;
    formDrawerRef.value.open()
}

const handleEdit = async (row) => {
    drawerTitle.value = '编辑'
    let res = await product_detail_api({ id: row.id })
    console.log('product detail: ', res)
    resetForm(res)
    res.productItemList.forEach(item => {
        if (item.lang == 'zh') {
            form.content = item.content
            console.log('form.content: ', form.content)
        } else if (item.lang == 'en') {
            form.contentEn = item.content
        }
    })
    let fileSuffix = ''
    if (res.handBookLink) {
        fileSuffix = getFileExtension(res.handBookLink)
        form.fileList = [{
            id: res.id,
            name: "操作手册" + res.id + '.' + fileSuffix,
            url: res.handBookLink,
            status: 'success',
            uid: res.id,
        }]
    }

    showSubBtn.value = true;
    editorRef_disable.value = false;
    formDrawerRef.value.open()
}

function getFileExtension(filename) {
    // 处理带查询参数的情况
    const cleanName = filename.split('?')[0];
    const parts = cleanName.split('.');
    return parts.length > 1 ? parts.pop().toLowerCase() : '';
}

/**
 * 展示详情
 * @param row 
 */
const handleDetail = async (row) => {
    drawerTitle.value = '详情'
    let res = await product_detail_api({ id: row.id })
    console.log('product detail: ', res)
    resetForm(res)
    res.productItemList.forEach(item => {
        if (item.lang == 'zh') {
            form.content = item.content
        } else if (item.lang == 'en') {
            form.contentEn = item.content
        }
    })

    let fileSuffix = ''
    if (res.handBookLink) {
        fileSuffix = getFileExtension(res.handBookLink)
        form.fileList = [{
            id: res.id,
            name: "操作手册" + res.id + '.' + fileSuffix,
            url: res.handBookLink,
            status: 'success',
            uid: res.id,
        }]
    }

    showSubBtn.value = false;
    formDrawerRef.value.open()
    editorRef_disable.value = true
}

const handleDelete = (row) => {
    console.log('delete row: ', { id: row.id })
    product_delete_api({ id: row.id }).then(res => {
        console.log('delete res: ', res)
        getData()
    })
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

function handleSubmit() {
    console.log(editorRef.value.valueHtml)

    form.content = editorRef.value.valueHtml
    form.contentEn = editorRef_en.value.valueHtml
    if (form.id == '') {
        form.productItemList = []
        form.productItemList.push({
            lang: 'zh', content: form.content
        })
        form.productItemList.push({
            lang: 'en', content: form.contentEn
        })
    } else {
        if (form.productItemList && form.productItemList.length >= 2) {
            form.productItemList.forEach(item => {
                if (item.lang == 'zh') {
                    item.content = form.content
                    item.lang = 'zh'
                } else {
                    item.content = form.contentEn
                    item.lang = 'en'
                }
            })
        } else {
            form.productItemList.push({
                lang: 'zh', content: form.content
            })
            form.productItemList.push({
                lang: 'en', content: form.contentEn
            })
        }

    }
    let paramIo = new FormData();
    if (!form.fileList || form.fileList.length < 1) {
        toast('操作手册不能为空', 'warning')
        return
    }
    form.fileList.forEach(file => {
        if (!file.id) {
            paramIo.append('files', file.raw)// 文件对象
        }
    })
    for (const key in form) {
        if (key == 'productItemList') {


        } else {
            paramIo.append(key, form[key])
        }

    }
    paramIo.append("productItemListStr", JSON.stringify(form.productItemList))
    // form.files = form.fileList;
    console.log('新增更新form: ', form)
    product_addOrUpdate_api(paramIo).then(res => {
        console.log('addOrUpdate res：', res)
        formDrawerRef.value.close()
        getData()
    })

}

//关闭
const isClosed = () => {
    //console.log("isClosed")
    // editorRef.value.destroyEditor()
    // editorRef_en.value.destroyEditor()
}

//重置searchForm
function resetSearchForm() {
    for (let key in searchFormInit) {
        searchForm[key] = searchFormInit.key;
    }

}

// ---------------- life --------------------
onMounted(() => {
    getProductTypeList()
    getData()
})

</script>

<style></style>